import { isArray } from 'lodash-es';
import { DirectiveBinding } from 'vue';

import { useUserStore } from '@/store';

function checkPermission(el: HTMLElement, binding: DirectiveBinding) {
  const userStore = useUserStore();
  const { permissions } = userStore;
  const { value } = binding;

  if (value) {
    let hasPermission = false;
    if (isArray(value)) {
      hasPermission = value.some((item) =>
        permissions?.includes(item)
      ) as boolean;
    } else {
      hasPermission = permissions?.includes(value) as boolean;
    }
    if (!hasPermission && el.parentNode) {
      el.parentNode.removeChild(el);
    }
  } else {
    throw new Error(
      `need permissions! Like v-permission="['System:User:Add','System:User:Edit']"`
    );
  }
}

export default {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding);
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding);
  },
};
